/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.core.context;

import io.iec.caf.data.jpa.repository.support.CafJpaLanguageThreadHolder;
import io.iec.caf.data.jpa.utils.TemporaryHibernateIdentifier;
import io.iec.edp.caf.boot.context.CAFContext;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.core.session.CafSession;
import io.iec.edp.caf.core.session.CafSessionContextHolder;
import io.iec.edp.caf.i18n.api.LanguageService;
import io.iec.edp.caf.i18n.api.LanguageSuffixProvider;
import io.iec.edp.caf.i18n.entity.EcpLanguage;
import org.hibernate.persister.entity.PersistersContext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 上下文设置包装类，方便后台线程设置session及语言上下文
 *
 * @author wangyandong
 */
public class CafContextWrapper {

    private final static HashMap<String, Map<String, String>> languageListCache = new HashMap<>();
    private LanguageService languageService;
    private LanguageSuffixProvider suffixProvider;

    public static CafContextWrapper current = new CafContextWrapper();
    private Lock lock = new ReentrantLock();

    protected CafContextWrapper() {
    }

    /**
     * 根据Session设置Session及语言上下文
     */
    public void setCurrentContext(CafSession session) {
        if (session != null) {
            //将Session设置为当前Session
            CafSessionContextHolder.setCurrentSession(session);

            //设置语言上下文
            String language = session.getLanguage();
            setCurrentLanguage(language);
        }
    }

    /**
     * 根据当前语言设置语言上下文
     */
    public void setCurrentLanguage(String language) {
        if (!TemporaryHibernateIdentifier.NATIVE) {
            String currentLangSuffix = getLanguageSuffixProvider().getFieldSuffix(language);

            //设置当前语言后缀
            String ctxLangSuffix = PersistersContext.getCurrentLangSuffix();
            if (!currentLangSuffix.equals(ctxLangSuffix))
                PersistersContext.setCurrentLangSuffix(currentLangSuffix);
        }

        //设置语言列表
        CafJpaLanguageThreadHolder.setLanguages(getLanguageList());
    }

    /**
     * 获取语言列表
     */
    private Map<String, String> getLanguageList() {
        String tenantId = String.valueOf(CAFContext.current.getTenantId());
        if (!languageListCache.containsKey(tenantId)) {
            try {
                lock.lock();
                if (!languageListCache.containsKey(tenantId)) {
                    List<EcpLanguage> languages = getLanguageService().getEnabledLanguages();
                    Map<String, String> langs = new HashMap<>();
                    for (EcpLanguage language : languages) {
                        if (language != null) {
                            langs.put(language.getId(), language.getFieldSuffix());
                        }
                    }
                    languageListCache.put(tenantId, langs);
                }
            } finally {
                lock.unlock();
            }
        }
        return languageListCache.getOrDefault(tenantId, null);
    }

    private LanguageService getLanguageService() {
        if (this.languageService == null)
            this.languageService = SpringBeanUtils.getBean(LanguageService.class);

        return this.languageService;
    }

    private LanguageSuffixProvider getLanguageSuffixProvider() {
        if (this.suffixProvider == null)
            this.suffixProvider = SpringBeanUtils.getBean(LanguageSuffixProvider.class);

        return this.suffixProvider;
    }

}
